package com.astoolkit.workflow.air
{
	import com.astoolkit.workflow.BaseTask;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	public class LoadTextFileFromUrl extends com.astoolkit.workflow.BaseTask
	{
		[Bindable]
		public var loadedContent : Object;
		
		[Inspectable(enumeration="text,e4x", defaultValue="text")]
		public var contentType : String = "text"; 
		
		public var url : String;
		
		
		override public function prepare() : void
		{
			super.prepare();
			loadedContent = null;
		}
		
		override public function begin() : void
		{
			super.begin();
			if( !url )
				fail( "Url not provided" );
			if( url.match( /^http(s)?:\/\// ) != null )
			{
				var request : URLLoader = new URLLoader();
				addSuspendableListener( request, Event.COMPLETE, onFileDownloaded );
				addSuspendableListener( request, IOErrorEvent.IO_ERROR, onFileDownloadError );
				addSuspendableListener( request, ProgressEvent.PROGRESS, onDownloadProgress );
				request.dataFormat = URLLoaderDataFormat.TEXT;
				request.load( new URLRequest( url ) );
				setProgress( 0 );
			}
			else 
			{
				var outFile : File = new File();
				outFile.url = url;
				if( !outFile.exists )
				{
					fail("Local file not found: " + outFile.nativePath );
					return;
				}
				var stream : FileStream = new FileStream();
				stream.open( outFile, FileMode.READ );
				var fileText : String;
				try
				{ 
					fileText = stream.readUTFBytes( stream.bytesAvailable );
				}
				catch( e : Error )
				{
					fail("Failed to read local file: " + outFile.nativePath );
					return;
				}
				
				textLoaded( fileText );
			}
			
		}

		private function onDownloadProgress( inEvent : ProgressEvent ) : void
		{
			setProgress( inEvent.bytesLoaded / inEvent.bytesTotal );
		}

		private function onFileDownloadError( inEvent : IOErrorEvent ) : void
		{
			fail( "Failed to download remote file");
		}
		
		private function onFileDownloaded( inEvent : Event ) : void
		{
			var loader : URLLoader = URLLoader( inEvent.target );
			
			textLoaded( loader.data != null ? loader.data as String : "" );
		}
		
		private function textLoaded( inText : String ) : void
		{
			if( contentType == "text" )
			{
				loadedContent = inText;
			}
			else
			{
				try 
				{
					loadedContent = new XML( inText );
				}
				catch( e : Error )
				{
					fail( "Loaded text is not valid XML" );
					return;
				}
			}
			complete();
		}
	}
}